/**
 * 
 */
package org.storagemanagement.DAO;

import java.text.ParseException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.springframework.stereotype.Repository;
import org.storagemanagement.DO.CustomerRelationshipDO;
import org.storagemanagement.constant.StorageConstant;
import org.storagemanagement.model.CustomerRelationshipQuery;
import org.storagemanagement.uti.CustomHibernateDaoSupport;

/**
 * @author Jason.zhang
 *
 */
@Repository("customerRelationshipDao")
public class CustomerRelationshipDaoImpl extends CustomHibernateDaoSupport implements  CustomerRelationshipDao{

	@Override
	public void add(CustomerRelationshipDO record) {
		getHibernateTemplate().save(record);
	}

	@Override
	public List<CustomerRelationshipDO> find(CustomerRelationshipQuery query) {
		Criteria criteria = getSession().createCriteria(CustomerRelationshipDO.class);
		if(StringUtils.isNotEmpty(query.getProductFrom())){
			criteria.add(Expression.like("productFrom", "%"+query.getProductFrom()+"%"));
		}
		if(StringUtils.isNotEmpty(query.getProductTo())){
			criteria.add(Expression.like("productTo", "%"+query.getProductTo()+"%"));
		}
		if(StringUtils.isNotEmpty(query.getProduct())){
			criteria.add(Expression.like("product", "%"+query.getProduct()+"%"));
		}
		
		if(query.getDateFrom() != null){
			try {
				criteria.add(Expression.ge("actionDate", StorageConstant.simpleDateFormat.parse(query.getDateFrom())));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		if(query.getDateTo() != null){
			String dateTo = query.getDateTo() + " 23:59:59";
			try {
				criteria.add(Expression.lt("actionDate", StorageConstant.dateFormatWithSeconds.parse(dateTo)));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		return criteria.list();
	}



}
